package com.jshan.utils;

import com.jshan.base.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class FileUploadUtils {

    @Value("${file.upload.path}")
    private String filePath;

    public Result upload(MultipartFile file, int type) {
        if (file.isEmpty()) {
            return Result.fail();
        }
        Map<String, String> map = new HashMap<>();
        // 获取日期目录 20250625 这种
        String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 这里是区分存储的是
        String fileDir = switch (type) {
            case 1 -> "/content/images/";
            case 2 -> "/content/files/";
            default -> "";
        };
        // 这里是完整的路径
        String fileUploadDir = filePath + fileDir + dateDir;
        File uploadDirFile = new File(fileUploadDir);
        if (!uploadDirFile.exists()) {
            if (uploadDirFile.mkdirs()) {
                log.info("目标目录不存在，已重新创建文件夹:{}", fileUploadDir);
            } else {
                log.error("目录文件夹创建失败:{}", fileUploadDir);
            }
        }
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        String fullFilePath = fileUploadDir + File.separator + fileName;
        try {
            file.transferTo(new File(fullFilePath));
            // 更新用户头像路径为相对路径，例如 /uploads/avatar/20250616/xxx.jpg
            String relativePath = "/uploads" + fileDir + dateDir + "/" + fileName;
            map.put("url", relativePath);
            return Result.ok(map);
        } catch (IOException e) {
            log.error("上传失败:{}", e.getMessage(), e);
            return Result.fail();
        }
    }
}
